//
//  WZPersonalController.m
//  ETong
//
//  Created by wanzhao on 15/10/28.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZOfficeSettingController.h"
#import "WZMineCell.h"
#import "WZMineItem.h"
#import "WZGroupItem.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "WZHelpController.h"
#import "WZUserInfoController.h"
#import "WZUpdateController.h"
#import "WZSettingController.h"
#import "MBProgressHUD+WZ.h"
#import "WZRootViewController.h"
#import "NetWorkShare.h"
#import "UIBarButtonItem+category.h"
#import "OAloginViewController.h"
#import "JKAlertDialog.h"

@interface WZOfficeSettingController ()<UITableViewDataSource, UITableViewDelegate, WZMineCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
- (WZGroupItem *)addGroupMineItem;
@property (nonatomic, strong) NSMutableArray *sectionItemArray;
@property (nonatomic, strong) CContactModel *curAccount;

/**OA userId*/
@property (nonatomic, strong) NSString *oaUserId;

@end

@implementation WZOfficeSettingController

- (void)dealloc
{
    NSLog(@"WZPersonalController dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    
    
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"title" title:nil target:self sel:@selector(lookPersonalInformation) titleFont:Font18 titleColor:ClearColor];
    self.navigationItem.title = @"办公设置";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, HARDWARE_SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ClearColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.view addSubview:self.tableView];
    
    //读取当前用户信息
//    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
//    self.curAccount = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
    
    
#pragma mark -- OA账号信息
    self.oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    
//    [self setupSection0];
    [self setupSection1];
//    [self setupSection2];
    
    // OA登入登出
    [self setupOAloginAndLogout];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
        
//    [MBProgressHUD showMessage:nil toView:nil];
    
    [NetWorkShare checkMobileWithUserId:self.oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:nil];
        NSString *mobileStr = @"";
        if (responseObject) {
            NSString *status =  [NSString stringWithFormat:@"%@",responseObject[@"status"]];
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                if ([status isEqualToString:@"2"]) {
                    mobileStr = @"已认证";
                    
                } else {
                    
                }
                
            } else {
                
                if ([status isEqualToString:@"-1"]) {
                    
                } else if ([status isEqualToString:@"0"]) {
                    
                } else if ([status isEqualToString:@"1"]) {
                    mobileStr = @"待审核";
                } else if ([status isEqualToString:@"3"]) {
                    mobileStr = @"审核被拒绝";
                }
                
            }
            
        } else {
            
        }
        [USER_DEFAULT setObject:mobileStr forKey:ISMOBILEAVALable];
        [USER_DEFAULT synchronize];
        
        WZGroupItem *group = self.sectionItemArray[0];
        WZMineItem *item4 = group.itemArray[0];
        if (M_ISSTRNULL(mobileStr)) {
            item4.title = @"手机认证";
            item4.isHiddenBackView = YES;
        } else {
            item4.title = [NSString stringWithFormat:@"手机认证(%@)",mobileStr];
            item4.isHiddenBackView = NO;
        }
        item4.isHiddenAccessView = YES;
        
        
        [self.tableView reloadData];
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:nil];
        
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:ADDGUESTURE object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:REMOVEGUESTURE object:nil];
}
- (void)lookPersonalInformation
{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    nav.navigationBarHidden = NO;
    self.navigationController.navigationBarHidden = YES;
    
    WZUserInfoController *info = [[WZUserInfoController alloc] init];
    [nav pushViewController:info animated:YES];
}

//- (void)setupSection0
//{
//    WZMineItem *item = [WZMineItem mineItemWithTitle:self.curAccount.UserName icon:@"personal_title"];
//    item.isHiddenBackView = YES;
//    item.subTitle = [NSString stringWithFormat:@"\n\n%@   %@",self.curAccount.DEPNAME,self.curAccount.Position];
//    item.isHiddenAccessView = NO;
//    item.destVc = [WZUserInfoController class];
//    item.isHeadImage = YES;
//    
//    WZGroupItem *groupItem = [self addGroupMineItem];
//    groupItem.itemArray = @[item];
//    
//}

- (void)setupSection1
{
//    WZMineItem *item = [WZMineItem mineItemWithTitle:@"设置" icon:@"setting_image"];
//    item.isHiddenAccessView = NO;
//    item.isHiddenBackView = YES;
//    item.destVc = [WZSettingController class];
//    
//    WZMineItem *item2 = [WZMineItem mineItemWithTitle:@"系统更新" icon:@"update_set_image"];
//    item2.isHiddenAccessView = NO;
//    item2.isHiddenBackView = YES;
//    item2.destVc = [WZUpdateController class];
//    
//    WZMineItem *item3 = [WZMineItem mineItemWithTitle:@"帮助中心" icon:@"help_image"];
//    item3.isHiddenAccessView = NO;
//    item3.isHiddenBackView = YES;
//    item3.destVc = [WZHelpController class];
    
    WZMineItem *item4 = [WZMineItem mineItemWithTitle:@"手机认证" icon:nil];
    NSString *mobleStr = [USER_DEFAULT stringForKey:ISMOBILEAVALable];
    if (M_ISSTRNULL(mobleStr)) {
        item4.title = @"手机认证";
        item4.isHiddenBackView = YES;
    } else {
        item4.title = [NSString stringWithFormat:@"手机认证(%@)",mobleStr];
        item4.isHiddenBackView = NO;
    }
    item4.isHiddenAccessView = YES;
    
    
    WZGroupItem *groupItem = [self addGroupMineItem];
    groupItem.itemArray = @[item4];
    
}

//- (void)setupSection2
//{
//    WZMineItem *item = [WZMineItem mineItemWithTitle:@"退出账户" icon:@"out_login_account"];
//    item.isHiddenAccessView = YES;
//    item.isHiddenBackView = YES;
//    item.block = ^(){
//        [MBProgressHUD showMessage:nil toView:self.view];
//        [NetWorkShare loginOutOAWithUserId:self.curAccount.UserID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
//            [MBProgressHUD hideHUDForView:self.view];
//            
//            if ([[responseObject objectForKey:@"success"] boolValue]) {
//                NSUserDefaults *userDefault = USER_DEFAULT;
//                [userDefault setBool:YES forKey:ISFORCEQUIT];
//                [userDefault synchronize];
//                
//                //判断是否清空缓存
//                if ([userDefault boolForKey:ISClEARMEMORY]) {
//                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                        __block NSFileManager *fileMg = [NSFileManager defaultManager];
//                        NSArray *array = [fileMg subpathsOfDirectoryAtPath:USER_DOCUMENT error:nil];
//                        [array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
//                            if ([fileMg fileExistsAtPath:obj]) {
//                                [fileMg removeItemAtPath:obj error:nil];
//                            }
//                        }];
//                        
//                    });
//                }
//                
//                UIApplication *app = [UIApplication sharedApplication];
//                app.statusBarHidden = NO;
//                app.statusBarStyle = UIStatusBarStyleLightContent;
//                
//                
//                
//                
//            } else {
//                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
//            }
//            
//            
//            
//        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
//            [MBProgressHUD hideHUDForView:self.view];
//            
//            [MBProgressHUD show:@"网络异常" icon:nil view:self.view];
//        }];
//    };
//    
//    
//    WZGroupItem *groupItem = [self addGroupMineItem];
//    groupItem.itemArray = @[item];
//}


- (void)setupOAloginAndLogout
{
    
#pragma mark -- OA账号登出
    WZMineItem *item = [WZMineItem mineItemWithTitle:@"退出办公" icon:nil];
    
    item.isHiddenAccessView = YES;
    item.isHiddenBackView = YES;
    item.block = ^(){
//        [MBProgressHUD showMessage:@"正在退出..." toView:self.view];
        [NetWorkShare loginOutOAWithUserId:self.oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                [USER_DEFAULT setBool:YES forKey:ISFORCEQUIT];
                [USER_DEFAULT synchronize];
                
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"确定退出办公账号?"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                    
                    // 清空缓存
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
                        [USER_DEFAULT removeObjectForKey:@"oaUserId"];
                        [USER_DEFAULT removeObjectForKey:@"oaPwd"];
                        [USER_DEFAULT removeObjectForKey:@"oaUserName"];
                        [USER_DEFAULT removeObjectForKey:@"oaCompanyID"];
                        
                        __block NSFileManager *fileMg = [NSFileManager defaultManager];
                        NSArray *array = [fileMg subpathsOfDirectoryAtPath:USER_DOCUMENT error:nil];
                        [array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                            if ([fileMg fileExistsAtPath:obj]) {
                                [fileMg removeItemAtPath:obj error:nil];
                            }
                        }];
                        
                    });
                    
                    OAloginViewController *oaLogin = [[OAloginViewController alloc] init];
                    [self presentViewController:oaLogin animated:YES completion:nil];
                }];
                
                [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                    // 取消后block回调
                }];
                [alert show];
                
                UIApplication *app = [UIApplication sharedApplication];
                app.statusBarHidden = NO;
                app.statusBarStyle = UIStatusBarStyleLightContent;
                
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD show:@"网络异常" icon:nil view:self.view];
        }];
    };
    
    WZGroupItem *groupItem = [self addGroupMineItem];
    groupItem.itemArray = @[item];
}


- (NSMutableArray *)sectionItemArray
{
    if (_sectionItemArray == nil) {
        _sectionItemArray = [NSMutableArray array];
    }
    return _sectionItemArray;
}

- (WZGroupItem *)addGroupMineItem
{
    WZGroupItem *item = [WZGroupItem groupMineItem];
    [self.sectionItemArray addObject:item];
    return item;
}

- (NSArray *)sectionArray
{
    return self.sectionItemArray;
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionItemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.sectionItemArray[section] itemArray].count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger count = [tableView numberOfRowsInSection:indexPath.section];
    
    WZMineCell *cell = [WZMineCell mineCellWithTableView:tableView];
    WZGroupItem *item = self.sectionItemArray[indexPath.section];
    if (count == 1 || indexPath.row == count - 1) {
        cell.line.hidden = YES;
    } else {
        cell.line.hidden = NO;
    }
    cell.item = item.itemArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = ClearColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return OppositeHeightRate(15);
    } else {
        return OppositeHeightRate(15);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return OppositeHeightRate(60);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WZGroupItem *groupitem = self.sectionItemArray[indexPath.section];
    WZMineItem *item = groupitem.itemArray[indexPath.row];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
//        [MBProgressHUD showMessage:nil toView:self.view];
        if ([[USER_DEFAULT objectForKey:ISMOBILEAVALable] isEqualToString:@"待审核"]) {
            NSLog(@"手机审核中。。。");
        }
        
        [NetWorkShare certifyMobileWithUserId:self.oaUserId phone:@"" simUuid:@"" mobileUuid:UUID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if (responseObject) {
                
                if ([[responseObject objectForKey:@"success"] boolValue]) {
                    [MBProgressHUD showSuccess:@"待审核"];
                    [USER_DEFAULT setObject:@"待审核" forKey:ISMOBILEAVALable];
                    [USER_DEFAULT synchronize];
                    item.title = @"待审核";
                    item.isHiddenBackView = NO;
                    [self.tableView reloadData];
                    
                } else {
                    if ([responseObject[@"message"] isKindOfClass:[NSNull class]]) {
                        
                        [MBProgressHUD showError:@"认证失败"];
                    } else {
                        [MBProgressHUD showError:responseObject[@"message"]];
                    }
                    
                }
                
            } else {
                [MBProgressHUD showError:@"未知错误"];
            }
            
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:@"网络错误"];
        }];
    }
    if (item.block != nil) {
        item.block();
    }
    
    if (item.destVc) {
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;
        
        UIViewController *vc = [[item.destVc alloc] init];
        [nav pushViewController:vc animated:YES];
    }
    
}


@end